﻿using System;
using System.Linq;

namespace Cfg.Helpers
{
    public static class TypeExtensions
    {
        /// <summary>
        /// Check if type has CompareTo method
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static bool IsComparable(this Type type)
        {
            return type.GetMethod("CompareTo", new[] {type}) != null;
        }

        /// <summary>
        /// Check if any base type of given type matches
        /// </summary>
        /// <param name="type"></param>
        /// <param name="baseType"></param>
        /// <returns></returns>
        public static bool IsInheritedFrom(this Type type, Type baseType)
        {
            var currentBaseType = type.BaseType;
            while (currentBaseType != null)
            {
                if (currentBaseType == baseType)
                    return true;

                currentBaseType = currentBaseType.BaseType;
            }

            return false;
        }

        /// <summary>
        /// Check if type implements given interface
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static bool Implements<TInterface>(this Type type)
        {
            return type.GetInterfaces().Contains(typeof(TInterface));
        }
        /*
        public static bool HasParseExtension(this Type type)
        {
            var mi = type.GetMethod("Parse", new[] { type, typeof(string) });
            return mi != null;
        }*/
    }
}